package com.bailian.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.math.BigDecimal;
import com.bailian.common.utils.DateUtils;
import com.bailian.common.exception.ServiceException;
import com.bailian.system.domain.BlParkTags;
import com.bailian.system.mapper.BlParkTagsMapper;
import com.bailian.system.domain.BlPark;
import com.bailian.system.mapper.BlParkMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bailian.system.mapper.BlWarehouseMapper;
import com.bailian.system.domain.BlWarehouse;
import com.bailian.system.domain.vo.BLWareHouseVo;
import com.bailian.system.service.IBlWarehouseService;
import com.bailian.system.utils.WarehouseVoConverter;
import com.bailian.system.utils.ParkVoConverter;
import com.bailian.system.domain.BlWarehouseType;

/**
 * 仓库基础信息Service业务层处理
 * 
 * @author bailian
 * @date 2025-08-04
 */
@Service
public class BlWarehouseServiceImpl implements IBlWarehouseService 
{
    @Autowired
    private BlWarehouseMapper blWarehouseMapper;

    @Autowired
    private BlParkTagsMapper blParkTagsMapper;

    @Autowired
    private WarehouseVoConverter warehouseVoConverter;

    @Autowired
    private BlParkMapper blParkMapper;

    @Autowired
    private ParkVoConverter parkVoConverter;

    /**
     * 查询仓库基础信息
     * 
     * @param warehouseId 仓库基础信息主键
     * @return 仓库基础信息
     */
    @Override
    public BlWarehouse selectBlWarehouseByWarehouseId(Long warehouseId)
    {
        return blWarehouseMapper.selectBlWarehouseByWarehouseId(warehouseId);
    }

    /**
     * 查询仓库基础信息列表
     * 
     * @param blWarehouse 仓库基础信息
     * @return 仓库基础信息
     */
    @Override
    public List<BlWarehouse> selectBlWarehouseList(BlWarehouse blWarehouse)
    {
        return blWarehouseMapper.selectBlWarehouseList(blWarehouse);
    }

    /**
     * 查询仓库基础信息VO列表
     * 
     * @param blWarehouse 仓库基础信息
     * @return 仓库基础信息VO集合
     */
    @Override
    public List<BLWareHouseVo> selectBlWarehouseVoList(BlWarehouse blWarehouse)
    {
        List<BLWareHouseVo> vos =  blWarehouseMapper.selectBLWareHouseVoList(blWarehouse);
        vos.forEach(item->{
           List<BlParkTags>  tags = new ArrayList<BlParkTags>();
            if (item.getWarehouseTags() != null) {
                item.getWarehouseTags().forEach(tagitem->{
                    BlParkTags tagss  = blParkTagsMapper.selectBlParkTagsByTagId(tagitem.getTagId());
                    if (tagss != null) {
                        tags.add(tagss);
                    }
                });
            }
            item.setWarehouseTags(tags);
            // 补充园区详情字段
            if (item.getParkInfo() != null && item.getParkInfo().getParkId() != null) {
                BlPark park = blParkMapper.selectById(item.getParkInfo().getParkId());
                if (park != null) {
                    item.setParkInfo(parkVoConverter.convertToVo(park));
                }
            }
        });
        return vos;
    }

    /**
     * 查询仓库基础信息VO
     * 
     * @param warehouseId 仓库基础信息主键
     * @return 仓库基础信息VO
     */
    @Override
    public BLWareHouseVo selectBlWarehouseVoByWarehouseId(Long warehouseId)
    {
        // 先查询仓库基础信息
        BlWarehouse warehouse = blWarehouseMapper.selectWarehouseBasicInfo(warehouseId);
        if (warehouse == null) {
            System.out.println("DEBUG: 仓库ID " + warehouseId + " 不存在");
            return null;
        }

        System.out.println("DEBUG: 查询到仓库基础信息: " + warehouse);
        System.out.println("DEBUG: 仓库类型ID: " + warehouse.getWarehouseType());

        // 转换为VO
        BLWareHouseVo vo = warehouseVoConverter.convertToVo(warehouse);
        
        // 查询仓库类型信息
        if (warehouse.getWarehouseType() != null) {
            System.out.println("DEBUG: 开始查询仓库类型，类型ID: " + warehouse.getWarehouseType());
            BlWarehouseType warehouseType = blWarehouseMapper.selectWarehouseTypeInfo(warehouse.getWarehouseType());
            System.out.println("DEBUG: 查询到的仓库类型: " + warehouseType);
            vo.setWarehouseType(warehouseType);
        } else {
            System.out.println("DEBUG: 仓库类型ID为null，跳过类型查询");
        }
        
        // 查询园区信息
        if (warehouse.getParkId() != null) {
            BlPark park = blParkMapper.selectById(warehouse.getParkId());
            if (park != null) {
                vo.setParkInfo(parkVoConverter.convertToVo(park));
            }
        }
        
        // 查询仓库标签信息
        if (warehouse.getWarehouseTags() != null && !warehouse.getWarehouseTags().isEmpty()) {
            List<BlParkTags> tags = new ArrayList<>();
            for (BlParkTags tagItem : warehouse.getWarehouseTags()) {
                if (tagItem.getTagId() != null) {
                    BlParkTags tag = blParkTagsMapper.selectBlParkTagsByTagId(tagItem.getTagId());
                    if (tag != null) {
                        tags.add(tag);
                    }
                }
            }
            vo.setWarehouseTags(tags);
        }
        
        return vo;
    }

    /**
     * 调试：查询仓库基础信息（不包含关联查询）
     * 
     * @param warehouseId 仓库ID
     * @return 仓库基础信息
     */
    @Override
    public BlWarehouse selectWarehouseBasicInfo(Long warehouseId)
    {
        return blWarehouseMapper.selectWarehouseBasicInfo(warehouseId);
    }

    /**
     * 调试：查询仓库类型信息
     * 
     * @param typeId 类型ID
     * @return 仓库类型信息
     */
    @Override
    public BlWarehouseType selectWarehouseTypeInfo(Long typeId)
    {
        if (typeId == null) {
            System.out.println("DEBUG: 类型ID为null，无法查询");
            return null;
        }
        
        System.out.println("DEBUG: 开始查询仓库类型，类型ID: " + typeId);
        
        // 先尝试直接查询
        BlWarehouseType result = blWarehouseMapper.selectWarehouseTypeInfo(typeId);
        System.out.println("DEBUG: 直接查询结果: " + result);
        
        // 如果查询失败，尝试使用原生SQL查询
        if (result == null) {
            System.out.println("DEBUG: 直接查询失败，尝试使用原生SQL查询");
            result = blWarehouseMapper.selectWarehouseTypeInfoRaw(typeId);
            System.out.println("DEBUG: 原生SQL查询结果: " + result);
        }
        
        return result;
    }

    /**
     * 调试：测试数据库连接和基本查询
     * 
     * @param typeId 类型ID
     * @return 测试结果
     */
    public String testDatabaseConnection(Long typeId)
    {
        try {
            System.out.println("=== 开始数据库连接测试 ===");
            
            // 测试1：查询仓库基础信息
            BlWarehouse warehouse = blWarehouseMapper.selectWarehouseBasicInfo(8L);
            System.out.println("测试1 - 仓库基础信息查询: " + (warehouse != null ? "成功" : "失败"));
            if (warehouse != null) {
                System.out.println("仓库类型ID: " + warehouse.getWarehouseType());
            }
            
            // 测试2：直接查询仓库类型
            BlWarehouseType type = blWarehouseMapper.selectWarehouseTypeInfo(typeId);
            System.out.println("测试2 - 仓库类型查询: " + (type != null ? "成功" : "失败"));
            if (type != null) {
                System.out.println("类型信息: " + type);
            }
            
            // 测试3：原生SQL查询
            BlWarehouseType typeRaw = blWarehouseMapper.selectWarehouseTypeInfoRaw(typeId);
            System.out.println("测试3 - 原生SQL查询: " + (typeRaw != null ? "成功" : "失败"));
            
            System.out.println("=== 数据库连接测试结束 ===");
            
            return "测试完成，请查看控制台日志";
            
        } catch (Exception e) {
            System.out.println("测试过程中发生异常: " + e.getMessage());
            e.printStackTrace();
            return "测试失败: " + e.getMessage();
        }
    }

    /**
     * 新增仓库基础信息
     * 
     * @param blWarehouse 仓库基础信息
     * @return 结果
     */
    @Override
    public int insertBlWarehouse(BlWarehouse blWarehouse)
    {
        // 验证必填字段
        validateWarehouseData(blWarehouse);
        // 处理仓库标签字段
        processWarehouseTags(blWarehouse);
        // 设置创建时间
        blWarehouse.setCreateTime(DateUtils.getNowDate());
        return blWarehouseMapper.insertBlWarehouse(blWarehouse);
    }

    /**
     * 修改仓库基础信息
     * 
     * @param blWarehouse 仓库基础信息
     * @return 结果
     */
    @Override
    public int updateBlWarehouse(BlWarehouse blWarehouse)
    {
        // 验证必填字段
        validateWarehouseData(blWarehouse);
        // 处理仓库标签字段
        processWarehouseTags(blWarehouse);
        // 设置更新时间
        blWarehouse.setUpdateTime(DateUtils.getNowDate());
        return blWarehouseMapper.updateBlWarehouse(blWarehouse);
    }

    /**
     * 批量删除仓库基础信息
     * 
     * @param warehouseIds 需要删除的仓库基础信息主键
     * @return 结果
     */
    @Override
    public int deleteBlWarehouseByWarehouseIds(Long[] warehouseIds)
    {
        return blWarehouseMapper.deleteBlWarehouseByWarehouseIds(warehouseIds);
    }

    /**
     * 删除仓库基础信息信息
     * 
     * @param warehouseId 仓库基础信息主键
     * @return 结果
     */
    @Override
    public int deleteBlWarehouseByWarehouseId(Long warehouseId)
    {
        return blWarehouseMapper.deleteBlWarehouseByWarehouseId(warehouseId);
    }

    /**
     * 验证仓库数据
     * 
     * @param blWarehouse 仓库基础信息
     */
    private void validateWarehouseData(BlWarehouse blWarehouse)
    {
        // 验证库房面积 - 必须为非空字符串
        if (blWarehouse.getAreaSize() == null || blWarehouse.getAreaSize().trim().isEmpty()) {
            throw new ServiceException("库房面积不能为空");
        }

        // 验证地面承重 - 必须为非空字符串
        if (blWarehouse.getFloorLoad() == null || blWarehouse.getFloorLoad().trim().isEmpty()) {
            throw new ServiceException("地面承重不能为空");
        }

        // 验证仓库名称 - 字符串类型，验证非空
        if (blWarehouse.getWarehouseName() == null || blWarehouse.getWarehouseName().trim().isEmpty()) {
            throw new ServiceException("仓库名称不能为空");
        }

        // 验证仓库名称 - 字符串类型，验证非空
        if (blWarehouse.getRentalPrice() == null) {
            throw new ServiceException("出租单价不能为空");
        }

        // 验证仓库名称 - 字符串类型，验证非空
        if (blWarehouse.getWarehouseType() == null) {
            throw new ServiceException("仓库类型不能为空");
        }
        // 验证仓库名称 - 字符串类型，验证非空
        if (blWarehouse.getIndustryDataId() == null) {
            throw new ServiceException("仓库行业不能为空");
        }
        // 验证详细地址 - 字符串类型，验证非空
        if (blWarehouse.getAddress() == null || blWarehouse.getAddress().trim().isEmpty()) {
            throw new ServiceException("详细地址不能为空");
        }

        // 验证所属园区 - Long类型，验证非空
        if (blWarehouse.getParkId() == null) {
            throw new ServiceException("所属园区不能为空");
        }
    }

    /**
     * 处理仓库标签字段
     * 
     * @param blWarehouse 仓库基础信息
     */
    private void processWarehouseTags(BlWarehouse blWarehouse)
    {
        // 如果warehouseTags字段为空或空列表，设置为null
        if (blWarehouse.getWarehouseTags() == null || blWarehouse.getWarehouseTags().isEmpty()) {
            blWarehouse.setWarehouseTags(null);
        }
    }

    @Override
    public void replaceWarehouseTags(Long warehouseId, List<Long> tagIds)
    {
        blWarehouseMapper.deleteWarehouseTagsByWarehouseId(warehouseId);
        if (tagIds != null && !tagIds.isEmpty()) {
            blWarehouseMapper.batchInsertWarehouseTags(warehouseId, tagIds);
        }
    }
}
